package com.hourse.app.utils;

import com.hourse.platform.common.ErrorMsg;
import com.hourse.platform.exception.ValidateException;
import com.hourse.platform.utils.StringTools;
import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator;
import org.springframework.util.ObjectUtils;

import java.util.regex.Pattern;

/**
 * @描述：【验证工具】
 * @作者：lichenguang
 * @创建：2021/11/24 9:20
 */
public class ValidationTools {

  /**
   * 验证空
   */
  public static void isNull(Object obj, String msg) throws ValidateException {

    if (ObjectUtils.isEmpty(obj)) {
      throw new ValidateException(ErrorMsg.BEAN_CHECK_ERR.code(), msg);
    }
  }

  /**
   * 验证非空
   */
  public static void isNotNull(Object obj, String msg) throws ValidateException {
    if (!ObjectUtils.isEmpty(obj)) {
      throw new ValidateException(ErrorMsg.BEAN_CHECK_ERR.code(), msg);
    }
  }

  public static void isMax(String str, int max, String msg) throws ValidateException {
    if (StringTools.isNotNull(str) && str.length() > max) {
      throw new ValidateException(ErrorMsg.BEAN_CHECK_ERR.code(), msg + "最大长度为" + str);
    }
  }


  /**
   * 验证是否为邮箱
   */
  public static void isEmail(String email, String msg) throws ValidateException {
    boolean valid = new EmailValidator().isValid(email, null);

    if (!valid) {
      throw new ValidateException(ErrorMsg.BEAN_CHECK_ERR.code(), msg);
    }

  }

  /**
   * 验证是否为手机号
   */
  public static void isPhone(String phone, String msg) throws ValidateException {
    Pattern pattern = Pattern.compile("1[3|4|5|7|8][0-9]\\d{8}");
    boolean matches = pattern.matcher(phone).matches();

    if (!matches) {
      throw new ValidateException(ErrorMsg.BEAN_CHECK_ERR.code(), msg);
    }
  }

  /**
   * 验证两个字符串是否不相等
   */
  public static void isNotEquals(String str1, String str2, String msg) throws ValidateException {

    if (!str1.equals(str2)) {
      throw new ValidateException(ErrorMsg.BEAN_CHECK_ERR.code(), msg);
    }
  }

  /**
   * 验证两个字符串是否相等
   */
  public static void isEquals(String str1, String str2, String msg) throws ValidateException {

    if (str1.equals(str2)) {
      throw new ValidateException(ErrorMsg.BEAN_CHECK_ERR.code(), msg);
    }
  }
}
